package com.anpy.anlibrary.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.anpy.anlibrary.model.BaseEntity
import com.anpy.anlibrary.net.NetWrapper
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel() {

    val listLiveData by lazy { MutableLiveData<BaseEntity>() }
    val errorLiveData by lazy { MutableLiveData<String>() }

    protected val jobs by lazy { mutableListOf<Job>() }

    fun <T : BaseEntity> NetWrapper<T>.response(callBack: (T) -> Unit) {
        onSuccess = {
            listLiveData.value = it
            callBack(it)
        }
        onError = {
            errorLiveData.value = it
        }
        onResponseError = {
            errorLiveData.value = it
        }
    }

//    protected val disposables by lazy { CompositeDisposable() }

    override fun onCleared() {
        close()
        super.onCleared()
    }

    private fun close() {
        jobs.forEach { it.cancel() }
    }

    var mutableLiveData:MutableLiveData<String> = MutableLiveData()

    fun launch(mutableLiveData:MutableLiveData<String>,block:()->Unit){
        viewModelScope.launch {
            block()
            mutableLiveData.value = "wpf"
        }
    }
}